package com.trkj.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.trkj.dao.jpa.IYzrMedPurchDAO;
import com.trkj.dao.jpa.IYzrMedPurchDetDAO;
import com.trkj.dao.jpa.IYzrMedicineDAO;
import com.trkj.dao.jpa.IYzrPurchOrderDAO;
import com.trkj.dao.jpa.IYzrPurchOrderDetDAO;
import com.trkj.dao.jpa.IYzrSupplierDAO;
import com.trkj.dao.jpa.IYzrTbstaffDAO;
import com.trkj.pojos.Tbstaff;
import com.trkj.pojos.YzrMedPurch;
import com.trkj.pojos.YzrMedPurchDet;
import com.trkj.pojos.YzrMedicine;
import com.trkj.pojos.YzrPurchOrder;
import com.trkj.pojos.YzrPurchOrderDet;
import com.trkj.pojos.YzrSupplier;
import com.trkj.vo.YzrOrderAndOrderDetVo;
import com.trkj.vo.YzrPurchOrderDetVo;
import com.trkj.vo.YzrPurchOrderVo;

@Service
@Transactional
public class YzrPurchOrderService {
	@Autowired
	private IYzrPurchOrderDAO yzrPurchOrderDAO;
	@Autowired
	private IYzrPurchOrderDetDAO yzrPurchOrderDetDAO;
	@Autowired
	private IYzrMedPurchDAO yzrMedPurchDAO;
	@Autowired
	private IYzrMedPurchDetDAO yzrMedPurchDetDAO;
	@Autowired
	private IYzrMedicineDAO yzrMedicineDAO;
	@Autowired
	private IYzrTbstaffDAO yzrTbstaffDAO;
	@Autowired
	private IYzrSupplierDAO yzrSupplierDAO;
	
	
	
	
	
	
	
	/**
	 * 根据交货时间段查询订单
	 * @param page
	 * @param rows
	 * @param startDate 
	 * @param endDate
	 * @return
	 */
	public Map<String, Object> queryByJiaoHuoDate(Date startDate,Date endDate,int page, int rows){
		PageRequest pr = new PageRequest(page - 1, rows);
		
		if(startDate.getTime() > endDate.getTime()){
			Date t = startDate;
			startDate = endDate;
			endDate = t;
		}
		List<YzrPurchOrder> list = yzrPurchOrderDAO.findOrderByJiaoHuoDate(startDate, endDate, pr);
		Map<String, Object> map = new HashMap<>();
		map.put("total", list.size());
		map.put("rows", purchOrderListToVo(list));		
		return map;
	}
	
	/**
	 * 根据不同条件查询订单信息
	 * @param page
	 * @param rows
	 * @param name
	 * @param value
	 * @return
	 */
	public Map<String, Object> queryByIf(int page, int rows,String name,String value){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrPurchOrder> list = new ArrayList<>();
		
		if(name.equals("name")){
			List<Tbstaff> staff = yzrTbstaffDAO.queryByStaffName(value);
			if(staff.size() > 0){
				for(Tbstaff s: staff){
					list = yzrPurchOrderDAO.findOrderByPeople(new BigDecimal(s.getStaffNo()), pr);
				}
			}					
		}else if(name.equals("checkState")){
			list = yzrPurchOrderDAO.findOrderByCheckState(value, pr);
		}else if(name.equals("rukuState")){
			list = yzrPurchOrderDAO.findOrderByRuKuState(value, pr);
		}else if(name.equals("orderId")){
			list = yzrPurchOrderDAO.findOrderById(value, pr);
		}	
		
		Map<String, Object> map = new HashMap<>();
		map.put("total", list.size());
		map.put("rows", purchOrderListToVo(list));
		
		return map;
	}
	
	/**
	 * 根据订单id查找订单
	 * @param orderId
	 * @return
	 */
	public YzrPurchOrderVo queryOrderById(String orderId){
		return purchOrderPoToVo(yzrPurchOrderDAO.findOne(orderId));
	}
	
	
	/**
	 * 根据订单id查找订单明细
	 * @param page
	 * @param rows
	 * @param orderId
	 * @return
	 */
	public Map<String, Object> queryOrderByOrderId(int page, int rows,String orderId){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrPurchOrderDet> list = yzrPurchOrderDetDAO.findOrderDetByOrderId(orderId,pr);
			
		Map<String, Object> map = new HashMap<>();
		map.put("total", list.size());
		map.put("rows", orderDetListToVo(list));
		return map;
	}
	private List<YzrPurchOrderDetVo> orderDetListToVo(List<YzrPurchOrderDet> list){
		if(list == null) return null;
		List<YzrPurchOrderDetVo> listVo = new ArrayList<>();
		
		for(YzrPurchOrderDet orderDet: list){
			YzrPurchOrderDetVo orderDetVo = orderDetPoToVo(orderDet);
			listVo.add(orderDetVo);
		}
		return listVo;
	}
	public YzrPurchOrderDetVo orderDetPoToVo(YzrPurchOrderDet orderDet){
		YzrPurchOrderDetVo orderDetVo = new YzrPurchOrderDetVo();
		
		orderDetVo.setOrderDetMedId(orderDet.getOrderDetMedId());;
		orderDetVo.setOrderDetMedName(orderDet.getOrderDetMedName());
		orderDetVo.setOrderDetBatchnumber(orderDet.getOrderDetBatchnumber());
		orderDetVo.setOrderDetGuige(orderDet.getOrderDetGuige());
		orderDetVo.setOrderDetMedUnit(orderDet.getOrderDetMedUnit());
		orderDetVo.setOrderDetMoney(orderDet.getOrderDetMoney());
		orderDetVo.setOrderDetNumber(orderDet.getOrderDetNumber());
		orderDetVo.setOrderDetOrderId(orderDet.getOrderDetOrderId());//订单id
		orderDetVo.setOrderDetPrice(orderDet.getOrderDetPrice());
		orderDetVo.setPurchOrderDetId(orderDet.getPurchOrderDetId());//订单明细id
		orderDetVo.setOrderDetSupId(orderDet.getOrderDetSupId());
		
		String supId = orderDet.getOrderDetSupId();
		
		if(supId != null){			
			YzrSupplier sup = yzrSupplierDAO.findOne(supId);		
			orderDetVo.setSupId(sup==null?null:sup.getSupId());
			orderDetVo.setSupName(sup==null?null:sup.getSupName());
		}
		return orderDetVo;
	}
	
	/**
	 * 查找出‘已验收’and‘未入库’的采购订单
	 */
	public Map<String,Object> queryAllOrderByNoInstock(int page, int rows){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrPurchOrder> list = yzrPurchOrderDAO.findAllOrderByNoInstock(pr);
		
		Map<String, Object> map = new HashMap<>();
		map.put("total", list.size());
		map.put("rows", purchOrderListToVo(list));
		return map;
	}

	/**
	 * 查找出‘未验收’and‘未入库’的采购订单
	 */
	public Map<String,Object> queryAllOrderByNoCheck(int page, int rows){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrPurchOrder> list = yzrPurchOrderDAO.findAllOrderByNoCheck(pr);
		
		Map<String, Object> map = new HashMap<>();
		map.put("total", list.size());
		map.put("rows", purchOrderListToVo(list));
		return map;
	}
	/**
	 * 分页 查询所有订单
	 * @param page
	 * @param rows
	 * @return
	 */
	public Map<String,Object> queryAllOrder(int page, int rows){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrPurchOrder> list = yzrPurchOrderDAO.findAllOrder(pr);
		long total = yzrPurchOrderDAO.count();
		
		Map<String, Object> map = new HashMap<>();
		map.put("total", total);
		map.put("rows", purchOrderListToVo(list));
		return map;
	}	
	private List<YzrPurchOrderVo> purchOrderListToVo(List<YzrPurchOrder> list){
		if(list == null) return null;
		List<YzrPurchOrderVo> listVo = new ArrayList<>();
		
		for(YzrPurchOrder purchOrder: list){
			YzrPurchOrderVo purchOrderVo = purchOrderPoToVo(purchOrder);
			listVo.add(purchOrderVo);
		}
		return listVo;
	}	
	public YzrPurchOrderVo purchOrderPoToVo(YzrPurchOrder purchOrder){
		YzrPurchOrderVo purchOrderVo = new YzrPurchOrderVo();
		purchOrderVo.setPurchOrderId(purchOrder.getPurchOrderId());
		purchOrderVo.setPurchPurchId(purchOrder.getPurchPurchId());
		purchOrderVo.setPurchInstockState(purchOrder.getPurchInstockState());
		purchOrderVo.setPurchJiaohuoAddress(purchOrder.getPurchJiaohuoAddress());
		purchOrderVo.setPurchJiaohuoDate(purchOrder.getPurchJiaohuoDate());
		purchOrderVo.setPurchOrderMoney(purchOrder.getPurchOrderMoney());
		purchOrderVo.setPurchOrderNumber(purchOrder.getPurchOrderNumber());
		purchOrderVo.setPurchYanshouState(purchOrder.getPurchYanshouState());
		purchOrderVo.setPurchYanshouResult(purchOrder.getPurchYanshouResult());
		purchOrderVo.setPurchOrderDate(purchOrder.getPurchOrderDate());
		purchOrderVo.setPurchPeople(purchOrder.getPurchPeople());
		
		BigDecimal zdr = purchOrder.getPurchPeople();
		
		if(zdr != null){		
			long sId = zdr.longValue();		
			Tbstaff staff = yzrTbstaffDAO.findOne(sId);	
			purchOrderVo.setStaffNo(staff==null?0:staff.getStaffNo());;
			purchOrderVo.setStaffName(staff==null?null:staff.getStaffName());
		}		
		
		return purchOrderVo;
	}
	
	
	/**
	 * 
	 * 查找出‘未采购’并且‘已通过’的采购计划单
	 * @return
	 */
	public Map<String,Object> queryStateAndAutState(int page, int rows){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrMedPurch> list = yzrMedPurchDAO.findByStateAndAutState(pr);
		Map<String, Object> map = new HashMap<>();
		map.put("total", list.size());
		map.put("rows", list);
		return map;
	}
	
	/**
	 * 根据计划单号查找出计划单下明细中的药品
	 * @param planId
	 * @return
	 */
	public Map<String, Object> queryMedByPlanId(String planId,int page, int rows){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrMedPurchDet> purchDets = yzrMedPurchDetDAO.findByPurchId(planId,pr);
		
		List<YzrMedicine> meds = new ArrayList<YzrMedicine>();
		
		for(YzrMedPurchDet purchDet: purchDets){
			YzrMedicine med = yzrMedicineDAO.findOne(purchDet.getPurchDetMedId());	
			meds.add(med);
		}
		Map<String, Object> map = new HashMap<>();
		map.put("total", meds.size());
		map.put("rows", meds);
		
		return map;
	}
	
	/**
	 * 添加采购订单
	 * @param purchOrder
	 */
	public void addPurchOrder(YzrOrderAndOrderDetVo purchOrder){
		// 获取年份
		String year = getNowDate();
		//拼接
		String name = "PO-" + year;	
		String nameDet = "OD-" + year;
		String n = yzrPurchOrderDAO.findID(name);
		System.out.println("从数据库中读取的最大采购编号："+n);
		
		BigDecimal sumMoney = new BigDecimal(0);
		
		YzrEntityService entityService = new YzrEntityService();
		String purId = entityService.getId(name, n);
		
		purchOrder.getPurchOrder().setPurchOrderId(purId);//保存id
		purchOrder.getPurchOrder().setPurchOrderNumber(new BigDecimal(purchOrder.getOrderDets().size()));	//订货项数
		purchOrder.getPurchOrder().setPurchYanshouState("未验收");//验收状态
	    														//验收结果
		
		
		purchOrder.getPurchOrder().setPurchInstockState("未入库");//入库状态
		yzrPurchOrderDAO.save(purchOrder.getPurchOrder());
		
		
		List<YzrPurchOrderDetVo> list = purchOrder.getOrderDets();
		
		
		if(list != null){
			for(YzrPurchOrderDetVo det: list){
				
				String nDet = yzrPurchOrderDetDAO.findID(nameDet);
				System.out.println("从数据库中读取的最大采购计划明细编号："+nDet);
				
				
				YzrPurchOrderDet orderDet = new YzrPurchOrderDet();
				//purchDetMedId，purchDetGuige，purchDetNumber，purchDetSupId，purchDetUnit
				orderDet.setOrderDetOrderId(entityService.getId(name, n));//采购id
				orderDet.setPurchOrderDetId(entityService.getId(nameDet, nDet));//明细id
				orderDet.setOrderDetMedName(det.getOrderDetMedName());//药品名
				orderDet.setOrderDetMedId(det.getPurchDetMedId());//药品id*
				orderDet.setOrderDetBatchnumber(det.getOrderDetBatchnumber());//批号
				orderDet.setOrderDetGuige(det.getPurchDetGuige());//规格*
				orderDet.setOrderDetMedUnit(det.getPurchDetUnit());//单位*
				orderDet.setOrderDetPrice(det.getOrderDetPrice());//单价
				orderDet.setOrderDetNumber(det.getPurchDetNumber());//数量*
				orderDet.setOrderDetMoney(det.getOrderDetMoney());//金额
				orderDet.setOrderDetSupId(det.getSupId());//供应商*
				
				sumMoney = sumMoney.add(det.getOrderDetMoney());
				yzrPurchOrderDetDAO.save(orderDet);
			}
			
			//修改采购计划单的采购状态
			System.out.println("计划id："+purchOrder.getPurchOrder().getPurchPurchId());
			String planId = purchOrder.getPurchOrder().getPurchPurchId();
			YzrMedPurch purchPlan = yzrMedPurchDAO.findOne(planId);
			purchPlan.setPurchState("已采购");
			yzrMedPurchDAO.save(purchPlan);
			
			purchOrder.getPurchOrder().setPurchOrderMoney(sumMoney);//订单金额
			yzrPurchOrderDAO.save(purchOrder.getPurchOrder());
		}
	}
	
	/**
	 * 格式化日期
	 * @return
	 */
	public static String getNowDate() {
		  Date currentTime = new Date();
		  SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		  String dateString = formatter.format(currentTime);
		  return dateString;
	}
}